<template>
  <div class="home">
    <nav class="navbar">
      <div class="container">
        <h1 class="navbar-title">心有灵“析”</h1>
        <div class="navbar-menu-wrapper">
          <ul class="navbar-menu">
            <li><el-button @click="handleDesign" v-if="isAdmin">设计表单</el-button></li>
            <li><el-button @click="handleCreate" v-if="isAdmin">创建表单</el-button></li>
            <li><el-button @click="handleChat">AI chat</el-button></li>
          </ul>
        </div>
        <button v-if="!isLogin" @click="goToLogin" class="login-button">登录/注册</button>
        <button v-else @click="loginOut" class="login-button">退出</button>
      </div>
    </nav>
    <div>
      <el-carousel :interval="4000" type="card" height="300px" width="90%" style="margin-top: 30px">
        <el-carousel-item v-for="item in lunboImgs" :key="item.id">
          <img :src="item.imgSrc" alt="轮播图" />
          <div class="carousel-item-text">
            <p>{{ item.description }}</p>
          </div>
        </el-carousel-item>
      </el-carousel>
      <router-view></router-view>
    </div>
    <div>
      <el-row class="row-bg" justify="space-around">
        <el-col :span="6">
          <div class="grid-content ep-bg-purple" />
          <el-form class="text-container">
            <h3>热门内容</h3>
            <p v-for="item in formList" @click="handleView(item)" class="text">
              <span class="label" v-for="label in getUniqueLabels(item)" :key="label" >{{ label }}</span>
              {{ item.title }}
            </p>
          </el-form>
          <el-pagination
            v-model:current-page="getFormListParams.pageNum"
            v-model:page-size="getFormListParams.pageSize"
            :small="small"
            :background="false"
            layout="prev, pager, next"
            :total="formTotal"
            @current-change="handleCurrentFormChange" />
        </el-col>
        <el-col :span="16">
          <div style="display: flex; flex-wrap: wrap; width: 100%; margin-top: 6vh">
            <div v-for="item in videoList" style="width: 30%; margin: 0 10px">
              <div @click="handlePlay(item)">
                <div style="height: 20vh">
                  <img style="border-radius: 10px" :src="item.images" :alt="item.title" />
                </div>

                <div class="description">{{ item.title }}</div>
              </div>
            </div>
          </div>
          <el-pagination
            v-model:current-page="getVideoListParams.pageNum"
            v-model:page-size="getVideoListParams.pageSize"
            :small="small"
            layout="prev, pager, next"
            :total="videoTotal"
            @current-change="handleCurrentChange" />
        </el-col>
      </el-row>
    </div>
    <div class="footer">
      <p>&copy; 2024 心有灵“析”</p>
      <ul>
        <li><a href="#">关于我们</a></li>
        <li><a href="#">服务条款</a></li>
        <li><a href="#">隐私政策</a></li>
        <li><a href="#">联系我们</a></li>
      </ul>
    </div>
    <el-dialog center v-model="dialogStatus.isVisible" :title="dialogStatus.title" width="1000" draggable>
      <el-form
        ref="ruleFormRef"
        style="max-width: 1000px"
        :model="formParams"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon>
        <el-form-item label="表单名称" prop="title">
          <el-input v-model="formParams.title" placeholder="请输入表单标题" />
        </el-form-item>
        <el-form-item label="表单介绍" prop="introduce">
          <el-input v-model="formParams.introduce" placeholder="请输入表单介绍" />
        </el-form-item>
        <el-form-item label="表单标签" prop="introduce">
          <el-select multiple v-model="formParams.tagIds" placeholder="请选择" size="large" style="width: 240px">
            <el-option v-for="item in formTagList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="表单内容" prop="formJson">
          <el-input
            type="textarea"
            placeholder="请先前往表单设计设计表单并复制JSON数据后粘贴到此处"
            :rows="6"
            v-model="formParams.formJson" />
        </el-form-item>
        <el-form-item v-show="formParams.result.globalResult.judges" label="表单规则" prop="introduce">
          <div v-for="item in formParams.result.globalResult.judges">
            <span>{{ getRulePrompt(item.formula) }}</span>
            <el-input v-model="item.explain" placeholder="请输入该分数的结果" />
          </div>
        </el-form-item>
        <el-form-item label="题目标签" prop="tag">
          <el-cascader
            :options="topicList"
            @change="handleTagChange"
            :props="props"
            collapse-tags
            validate-event
            placeholder="请先填入表单内容"
            :disabled="!topicList.length"
            collapse-tags-tooltip />
        </el-form-item>
        <div v-show="formParams.result.tagResult.length > 0">
          <el-form-item v-for="item in formParams.result.tagResult" :label="item.title" prop="tag">
            <div v-for="subItem in item.judges" style="width: 100%">
              {{ getRulePrompt(subItem.formula) }} :
              <el-input width="100" placeholder="请输入此时的结论" v-model="subItem.explain"></el-input>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div style="display: flex; justify-content: end">
        <el-button @click="handleSubmit">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      @close="handleClosePlayerDialog"
      center
      v-model="dialogStatus.isPlayerVisible"
      :title="dialogStatus.title"
      draggable>
      <div :id="'player-' + curVideoId" style="width: 100%; height: 70vh; margin: auto"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch, nextTick } from "vue";
import { useRouter } from "vue-router";
import { group, concatAndRemoveDuplicates } from "../../utils/commonTool";
import { getTagList as getTagListApi, getFormList as getFormListApi, addForm as addFormApi } from "../../api/home";
import { login as loginApi } from "@/api/login";
import to from "await-to-js";
import { ElMessage } from "element-plus";
import { getVideoList as getVideoListApi, getPlayAuth as getPlayAuthApi } from "../../api/video";

// 进行热门内容标签的显示
const customLabels = ref(['测试表单', '抑郁', '焦虑']);
// 计算属性，为每个 formList 项生成唯一标签组合
const getUniqueLabels = (item) => {
  // 检查title中是否包含"抑郁"关键词
  if (item.title.includes("抑郁")) {
    return "抑郁";
  }
  // 检查title中是否包含"焦虑"关键词
  if (item.title.includes("焦虑")) {
    return "焦虑";
  }
  // 检查title中是否包含"障碍"关键词
  if (item.title.includes("障碍")) {
    return "心理障碍";
  }
  // 如果都不包含，则返回"自测"
  return "自测";
};

const formParams = reactive({
  title: "",
  introduce: "",
  content: "",
  tagIds: [],
  formJson: "",
  options: [],
  result: {
    tagResult: [],
    globalResult: [],
  },
});

const getVideoListParams = reactive({
  pageSize: 6,
  pageNum: 1,
  // isAsc: "desc",
  orderByColumn: "createTime",
  isAsc: "asc",
});
const videoTotal = ref(0);
const videoList = ref([]);
const getVideoList = async () => {
  console.log(isAdmin.value);
  if (isAdmin.value) {
    getVideoListParams.isAsc = "asc";
  } else {
    getVideoListParams.isAsc = "desc";
  }
  const [err, res] = await to(getVideoListApi(getVideoListParams));
  if (!err) {
    console.log(res);
    videoList.value = res.rows;
    videoTotal.value = res.total;
  }
};

const handleCurrentChange = async (value) => {
  console.log(value);
  getVideoListParams.pageNum = value;
  await getVideoList();
};

// 标签规则模板
const SCORE_TEMPLATE = {
  describe: "",
  tagId: "",
  judges: [
    {
      formula: "",
      explain: "",
    },
    {
      explain: "",
      formula: "",
    },
    {
      explain: "",
      formula: "",
    },
  ],
};
// 标签选择一次固定分数
const TAG_CHECKED_SCORE = 9;
// 联级选择器配置
const props = { multiple: true };
let topicTagList = reactive([]);
let formTagList = reactive([]);
let formList = ref([]);
const isLogin = ref(false);
const isAdmin = ref(false);
onMounted(() => {
  isLogin.value = localStorage.getItem("token") ? true : false;
  if (localStorage.getItem("isAdmin")) {
    isAdmin.value = localStorage.getItem("isAdmin") == "false" ? false : true;
  } else {
    isAdmin.value = false;
  }
  getVideoList();
  console.log(isAdmin.value);
});

const loginOut = () => {
  isLogin.value = false;
  localStorage.clear();
};
// 挂载钩子
onMounted(async () => {
  topicTagList = await getTagList({ ...getTagListParams, categoryId: "673234945" });
  formTagList = await getTagList({ ...getTagListParams });
  getFormList();
});
let topicList = reactive([]);

// 表单规则
const rules = reactive({
  title: [
    { required: true, message: "请输入表单名称", trigger: "blur" },
    { min: 3, max: 15, message: "长度限制在3-15之间", trigger: "blur" },
  ],
  content: [{ required: true, message: "表单内容为必填项，请输入已设计的表单！", trigger: "blur" }],
});
const ruleFormRef = ref(null);
// 跳转设计表单页面
const handleDesign = () => {
  router.push("/formCreate");
};

// 粘贴表单后获取量表规则
watch(
  () => formParams.formJson,
  (newVal, oldVal) => {
    formParams.result.globalResult = getGlobalResult();
  }
);
// 初始化联级选择器
topicList = computed(() => {
  if (formParams.formJson) {
    return JSON.parse(formParams.formJson).widgetList.map((item, index) => {
      const currentObj = {
        label: item.options.label,
        value: item.options.name,
        children: JSON.parse(JSON.stringify(topicTagList)),
      };
      return currentObj;
    });
  } else {
    return [];
  }
});
// 获取标签参数
const getTagListParams = reactive({
  pageSize: 10,
  pageNumber: 1,
});
// 获取tag列表
const getTagList = async (params) => {
  const [err, res] = await to(getTagListApi(params));
  if (!err) {
    res.rows.forEach((item) => {
      item.children = [];
      item.value = item.tagId;
      item.label = item.content;
    });
    return res.rows;
  } else {
    ElMessage({
      type: "error",
      message: "获取标签列表失败",
    });
  }
};
// 已过滤已勾选的标签列表
const filteredCheckedTagList = ref([]);
// 已勾选未过滤的标签列表
const checkedTagList = ref([]);
// 题目tag选择改变时
const handleTagChange = (value) => {
  const cur = value.map((item) => {
    return {
      sort: item[0],
      tag: item[1],
    };
  });
  console.log(value, cur);
  // 先清空
  filteredCheckedTagList.value = [];
  checkedTagList.value = [];
  for (let subItem of cur) {
    if (!filteredCheckedTagList.value.includes(subItem.tag)) {
      // 获取已勾选且过滤了的的所有tag
      filteredCheckedTagList.value.push(subItem.tag);
    }
    // 获取已勾选未过滤的tag
    checkedTagList.value.push(subItem.tag);
  }
  console.log(filteredCheckedTagList.value);
  // 缓存之前的tag规则
  const preTagResult = JSON.parse(JSON.stringify(formParams.result.tagResult));
  // 记录当前变化后的规则
  const currentResult = [];
  formParams.result.tagResult = [];
  // 遍历已勾选已过滤的tag生成标签
  filteredCheckedTagList.value.forEach((item) => {
    const currentTemplate = { ...SCORE_TEMPLATE };
    // 设置tagId
    currentTemplate.tagId = item;
    // 设置描述
    currentTemplate.describe = findDescribe(item);
    // 设置title
    currentTemplate.title = findTitle(item);
    // 获取标签的最高分
    let hightestScore = getHightestScore(item);
    // 获取标签判定规则
    currentTemplate.judges = getJudges(hightestScore);
    // 标签判定规则加入表单params
    currentResult.push(currentTemplate);
  });
  // 对比缓存和当前的规则对象，生成合并的对象
  formParams.result.tagResult = compareOldAndNew(preTagResult, currentResult);
  // 根据题号排序
  const groupedObj = group(cur, "sort");
  // 清空之前的
  formParams.options = [];
  for (let subItem in groupedObj) {
    formParams.options.push({
      sort: subItem,
      tagIds: groupedObj[subItem],
    });
  }
};

// 找到描述字段
const findDescribe = (id) => {
  let index = topicTagList.findIndex((item) => item.tagId == id) + 1;
  if (index) {
    index--;
    return topicTagList[index].remark;
  } else {
    return "未找到描述字段";
  }
};
// 找到tag标题
const findTitle = (id) => {
  let index = topicTagList.findIndex((item) => item.tagId == id) + 1;
  if (index) {
    index--;
    return topicTagList[index].label;
  } else {
    return "未找到该标签";
  }
};
// 获取标签的分数
const getHightestScore = (id) => {
  let sum = 0;
  checkedTagList.value.forEach((item) => {
    if (item === id) sum = sum + TAG_CHECKED_SCORE;
  });
  return sum;
};
// 获取标签判断规则
const getJudges = (hightestScore) => {
  return [
    {
      explain: "",
      formula: `#score<${hightestScore / 3}`,
    },
    {
      explain: "",
      formula: `#score>=${hightestScore / 3} and #score<=${(hightestScore * 2) / 3}`,
    },
    {
      explain: "",
      formula: `#score>${(hightestScore * 2) / 3}`,
    },
  ];
};
// 对比缓存前和当前的规则对象，生成合并的对象
const compareOldAndNew = (oldResult, newResult) => {
  // 循环新的，去匹配旧的
  return newResult.map((item) => {
    for (let subItem of oldResult) {
      // 匹配到了
      if (item.tagId == subItem.tagId) {
        item.judges[0].explain = subItem.judges[0].explain;
        item.judges[1].explain = subItem.judges[1].explain;
        item.judges[2].explain = subItem.judges[2].explain;
        break;
      }
    }
    return item;
  });
};

// 获取规则提示
const getRulePrompt = (content) => {
  return content.replace(/#score/g, "分数");
};

// 获取量表规则
const getGlobalResult = () => {
  const curMaxScore = JSON.parse(formParams.formJson).widgetList.length * 6;
  return {
    judges: [
      {
        formula: `#score < ${curMaxScore / 3}`,
        explain: ``,
      },
      {
        explain: ``,
        formula: `#score >=${curMaxScore / 3} and #score <${(curMaxScore * 2) / 3}`,
      },
      {
        explain: ``,
        formula: `#score >= ${(curMaxScore * 2) / 3}`,
      },
    ],
    describe: "",
  };
};

const getFormListParams = reactive({
  pageSize: 10,
  pageNum: 1,
  // tagIds: localStorage.getItem("tags") || "",
  // isAsc: "desc",
  // isAsc: "asc",
  orderByColumn: "createTime",
});
console.log(localStorage.getItem("tags"));
const formTotal = ref(0);
// 获取表单列表
const getFormList = async () => {
  if (isAdmin.value) {
    const [err, res] = await to(
      getFormListApi({
        pageSize: 10,
        pageNum: 1,
        isAsc: "asc",
        orderByColumn: "createTime",
      })
    );
    if (!err) {
      formList.value = res.rows;
      formTotal.value = res.total;
    }
  } else {
    getFormListParams.isAsc = "desc";
    const [err, res] = await to(getFormListApi(getFormListParams));
    if (!err) {
      formList.value = res.rows.slice(0,4);
      formTotal.value = res.total;
    }
  }
};

const handleCurrentFormChange = async (value) => {
  getFormListParams.pageNum = value;
  await getFormList();
};
// dialog状态
const dialogStatus = reactive({
  isPlayerVisible: false,
  isVisible: false,
  title: "",
});

// 打开创建表单dialog
const handleCreate = () => {
  dialogStatus.isVisible = true;
  dialogStatus.title = "创建表单";
};

// 查看表单
const handleView = (item) => {
  if (isLogin.value) {
    router.push({
      path: "/formView",
      query: {
        formJson: JSON.parse(item.formJson),
        formDetail: JSON.stringify(item),
      },
    });
  } else {
    ElMessage({
      type: "warning",
      message: "请先登录后再填写表单哦~",
    });
  }
};

// 跳转ai聊天
const handleChat = () => {
  router.push({
    path: "/chat",
    query: {
      userId: "8213486349128123",
      appid: "232f45794d1b4ac07c9f353324922e6c",
    },
  });
};

// 确定提交
const handleSubmit = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 验证通过
      const [err, res] = await to(addFormApi(formParams));
      if (!err) {
        dialogStatus.isVisible = false;
        dialogStatus.title = "";
        ElMessage({
          type: "success",
          message: "新增成功",
        });
      }
    }
  });
};
// 关闭dialog
const handleClose = () => {
  dialogStatus.isVisible = false;
  dialogStatus.title = "";
};
const lunboImgs = ref([
  {
    id: 1,
    imgSrc: "https://picx.zhimg.com/v2-33aecdbc1b831cb634b03509c541b547_r.jpg?source=1def8aca",
    description: "向学校、个人、单位等提供多种心理测量服务和心理健康服务",
  },
  {
    id: 2,
    imgSrc: "https://pic1.zhimg.com/v2-9b293f986053998cb6a3220ffc942df7_r.jpg?source=1def8aca",
    description: "在线与心理医生进行聊天治疗",
  },
  {
    id: 3,
    imgSrc: "https://picx.zhimg.com/80/v2-8dad328087befaf88405f59dc1853146_1440w.webp?source=1def8aca",
    description: "用户也可在该平台的广场中与其他用户交流心得",
  },
  {
    id: 4,
    imgSrc: "https://picx.zhimg.com/v2-4f4857032a33be5052e1b859b1c5ab9e_r.jpg?source=1def8aca",
    description: "拥有专属用户的AI-friend，能够不限时不限区的与用户沟通",
  },
]);
const router = useRouter();
const goToLogin = () => {
  router.push({ path: "/login" });
};
const videoPlayer = ref(null);
const curVideoId = ref("");
const handlePlay = async (row) => {
  dialogStatus.isPlayerVisible = true;
  dialogStatus.title = row.title;
  curVideoId.value = row.videoId;
  console.log(row);
  // 获取播放凭证
  const [err, res] = await to(getPlayAuthApi(row.videoId));
  if (!err) {
    console.log(res);
    nextTick(() => {
      videoPlayer.value = new Aliplayer({
        id: "player-" + row.videoId,
        width: "100%",
        vid: res.data.vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
        playauth: res.data.playAuth, //必选参数。音视频播放凭证。
        autoplay: true,
        preload: true,
      });
    });
  } else {
  }
};

const handleClosePlayerDialog = () => {
  if (videoPlayer.value) {
    videoPlayer.value.dispose();
  }
};
</script>

<style scoped>
.home {
  background: linear-gradient(to bottom, #a6caeb, #bee6cb, #87ddc5); /* 渐变色 */
  height: 100%;
}
.navbar {
  background: linear-gradient(to bottom, #bee6cb, #a6caeb); /* 渐变色 */
  color: #fff;
  padding: 10px 0;
}

.container {
  padding: 10px;
  display: flex;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.navbar-title {
  font-size: 24px;
  margin: 0;
}

.navbar-menu-wrapper {
  display: flex;
  justify-content: center; /* Center the navigation links */
  flex: 1; /* Fill the remaining space */
}

.navbar-menu {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

.navbar-menu li {
  margin-right: 20px;
}

.navbar-menu li:last-child {
  margin-right: 0;
}

.navbar-menu a {
  color: #fff;
  text-decoration: none;
  font-size: 18px;
}

.navbar-menu a:hover {
  text-decoration: underline;
}

.login-button {
  padding: 5px 10px;
  background-color: transparent;
  color: #fff;
  border: 1px solid #fff;
  border-radius: 5px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  margin-left: auto;
}

.login-button:hover {
  background-color: #ffffff;
  color: #a7e6bb;
}

img {
  width: 100%;
  height: 100%;
}

.carousel-item-text {
  position: absolute;
  bottom: 0; /* 或者 top: 0; 根据你的布局需求 */
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  color: white; /* 文字颜色 */
  width: 100%;
  height: 100%;
  text-align: center; /* 文字居中 */
  font-size: 30px;
}

.carousel-item-text h3 {
  padding: 10px;
  margin-top: 30px;
}
.text:hover {
  text-decoration: underline; /* 鼠标悬停时添加下划线效果 */
  font-family: "Comic Sans MS", cursive; /* 应用艺术字体 */
}

.label {
  /* 设置标签样式 */
  background-color: #389a6a; /* 深绿色 */
  color: white; /* 标签文字颜色 */
  padding: 5px 10px; /* 内边距 */
  border-radius: 5px; /* 圆角 */
  /* margin-bottom: 10px; 标签与内容之间的间距 */
  margin-right: 8px;
  font-size: 16px; /* 标签字体大小 */
  font-weight: bold; /* 加粗标签文字 */
  display: inline-block; /* 使标签水平显示 */
}
.carousel-item-text p {
  margin: 10vh 0 0 0;
}

.grid-content {
  border-radius: 10px;
  min-height: 36px;
  margin-top: 20px;
}

.text-container {
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 文字溢出时显示省略号 */
  white-space: nowrap; /* 防止文字换行 */
  border: 1px solid #f1e3e3; /* 添加边框样式 */
  padding: 10px;
}

.text {
  cursor: pointer; /* 鼠标样式，使文本看起来像链接 */
}

.text:hover {
  text-decoration: underline; /* 鼠标悬停时添加下划线效果 */
  font-family: 'Comic Sans MS', cursive; /* 应用艺术字体 */
}

.label {
  /* 设置标签样式 */
  background-color: #389a6a; /* 深绿色 */
  color: white; /* 标签文字颜色 */
  padding: 5px 10px; /* 内边距 */
  border-radius: 5px; /* 圆角 */
  //margin-bottom: 10px; /* 标签与内容之间的间距 */
  margin-right: 8px;
  font-size: 16px; /* 标签字体大小 */
  font-weight: bold; /* 加粗标签文字 */
  display: inline-block; /* 使标签水平显示 */
}

.footer {
  background-color: #294238;
  color: #fff;
  text-align: center;
  width: 100%;
  bottom: 0;
}

.footer ul {
  list-style: none;
  padding: 0;
}

.footer li {
  display: inline-block;
  margin-right: 10px;
}

.footer a {
  color: #fff;
  text-decoration: none;
}

.image-form {
  /* 根据需要添加样式 */
}

.image-row {
  display: flex;
  justify-content: space-around;
  /* 根据需要添加样式 */
}

.image-card {
  width: auto;
  padding: 10px;
  /* 根据需要添加样式 */
}

.image {
  width: 100%;
  height: auto;
  /* 根据需要添加样式 */
}
.description {
  padding: 10px; /* 描述的上下边距 */
  /* 根据需要添加样式 */
}
.el-pagination {
  background-color: #f5f5f5; /* 设置背景色为页面背景色 */
  /* 根据需要添加样式 */
}
</style>
